import { history } from 'umi';
import type { RunTimeLayoutConfig, RequestConfig } from 'umi';
import { Local } from './utils/storage';
import { PageLoading } from '@ant-design/pro-layout';
import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import RightContent from '@/components/RightContent';
// import Footer from '@/components/Footer';

import service from './services';

const loginPath = '/user/login';

export const initialStateConfig = {
  loading: <PageLoading />,
};

export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: User.CurrentUser;
  fetchUserInfo?: () => Promise<User.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const { data } = await service.user.currentUser();
      return data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: [],
    menuHeaderRender: undefined,
    ...initialState?.settings,
  };
};

export const request: RequestConfig = {
  errorConfig: {
    errorPage: loginPath,
  },
  requestInterceptors: [
    (url: any, options: any) => {
      const token = Local?.get('token');
      if (options.requestType === 'form') {
        options.data.append('token', token);
      } else {
        options.data = {
          ...options.data,
          ...{
            token,
          },
        };
      }
      return {
        url,
        options,
      };
    },
  ],
};
